package hn.cch.hive.udf;

import org.apache.hadoop.hive.ql.exec.Description;
import org.apache.hadoop.hive.ql.exec.UDFArgumentException;
import org.apache.hadoop.hive.ql.exec.UDFArgumentLengthException;
import org.apache.hadoop.hive.ql.exec.UDFArgumentTypeException;
import org.apache.hadoop.hive.ql.metadata.HiveException;
import org.apache.hadoop.hive.ql.udf.generic.GenericUDF;
import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspector;
import org.apache.hadoop.hive.serde2.objectinspector.primitive.PrimitiveObjectInspectorFactory;
import org.apache.hadoop.hive.serde2.objectinspector.primitive.StringObjectInspector;

@Description(
        name = "custom_generic_udf",
        value = "custom_generic_udf(): desc",
        extended = "example: usage"
)
public class CustomGenericUDF extends GenericUDF {

    StringObjectInspector xObjectInspector;
    StringObjectInspector yObjectInspector;

    @Override
    public ObjectInspector initialize(ObjectInspector[] objectInspectors) throws UDFArgumentException {
        if (objectInspectors.length != 2) {
            throw new UDFArgumentLengthException("args size need 2");
        }

        ObjectInspector x = objectInspectors[0];
        ObjectInspector y = objectInspectors[1];
        // if (!(x instanceof StringObjectInspector) || !(y instanceof StringObjectInspector)) {
        //     throw new UDFArgumentTypeException(0, "args type need same");
        // }
        this.xObjectInspector = (StringObjectInspector) x;
        this.yObjectInspector = (StringObjectInspector) y;
        return PrimitiveObjectInspectorFactory.javaStringObjectInspector;

    }

    @Override
    public Object evaluate(DeferredObject[] deferredObjects) throws HiveException {
        String x = String.valueOf(this.xObjectInspector.getPrimitiveJavaObject(deferredObjects[0].get()));
        String y = String.valueOf(this.yObjectInspector.getPrimitiveJavaObject(deferredObjects[1].get()));
        return x + y;
    }

    @Override
    public String getDisplayString(String[] strings) {
        return String.join(",", strings);
    }
}
